package com.xxx.config.exception.support;

import com.xxx.config.exception.ErrorResponseStatusCode;
import com.xxx.config.exception.GenExceptCode;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

/**
 * 处理校验异常
 *
 * @version 1.0
 * @since 1.0
 */
public class ValidationExceptionMapperSupport implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException e) {
        ValidateMsg v = new ValidateMsg();
        v.code = GenExceptCode.Request_Param.name();
        final StringBuilder strBuilder = new StringBuilder();
        if (e instanceof ConstraintViolationException) {
            for (ConstraintViolation<?> cv : ((ConstraintViolationException) e)
                    .getConstraintViolations()) {
                strBuilder.append(cv.getPropertyPath().toString()).append(":").append(cv.getMessage()).append(",");
            }
        } else {
            strBuilder.append(e.getMessage());
        }
        v.msg = StringUtils.removeEnd(strBuilder.toString(), ",");
        return Response.ok(v, MediaType.APPLICATION_JSON).status(ErrorResponseStatusCode.SERVICE_ERROR).build();
    }

    /**
     * 存储validate message
     */
    @Data
    private static class ValidateMsg {
        private String code;
        private String msg;
    }
}
